﻿using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Xrm.Solutions.FrameworkSample.Common
{
    public class CreditLimitServiceCRM: ICreditLimitServiceCRM
    {
        private IIdentityCheckService Service { get; set; }
        private IOrganizationService CRMService { get; set; }

        public CreditLimitServiceCRM(IIdentityCheckService service,
                                    IOrganizationService crmService)
        {
            Service = service;
            CRMService = crmService;
        }
        
        public int IncreaseLimit(Guid contactId,
                                int requestedLimit)
        {
            Entity contact = CRMService.Retrieve("contact", contactId, new ColumnSet(true));

            string firstname = contact["firstname"].ToString();
            string lastname = contact["lastname"].ToString();
            DateTime dob = (DateTime)contact["birthdate"];
            string address = contact["address"].ToString();
            int currentLimit = (int)contact["xrm_currentlimit"];

            int score = Service.RunCheck(firstname,
                                            lastname,
                                            dob,
                                            address);

            if (score > 90)
            {
                if (requestedLimit < (int)(currentLimit * 1.5))
                {
                    return requestedLimit;
                }
                else
                {
                    return (int)(currentLimit * 1.5);
                }
            }
            else
            {
                return currentLimit;
            }
        }
    }
}
